import { formatGMTDate, toPercent, arrayToObject } from '../../../../assets/js/util.js'
import advance from '../advancedFilter.vue'
import echarts from 'echarts'
export default {
    data() {
        return {
            // 默认参数 和 URL
            SRC: '',
            DP: {
                p: '',
                f: ''
            },
            // title
            title: "付费习惯",
            /* 的宽*/
            pageWidth: '100%',
            /*当前页显示数量*/
            pageSize: 10,
            /*每页显示的数量*/
            pageSizes: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal: 0,
            /*分页器*/
            currentPage: 1,
            // 选择的时间
            date: '',
            // 渠道数组
            plats: [],
            // 渠道数组
            channels: [],
            // 服务器数组
            servers: [],
            // 切换人数和金额的菜单
            chartsName: "人数",
            // 首付等级分布金额/人数数据
            firstPayLevelChart: [],
            firstPayLevelChart1: [],
            // 默认的一些时间范围
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近15天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            postObj: {
                dstart: '',
                dend: '',
                platform: '0',
                channel: '0',
                server: '0'
            },
            activeName: '1',
            /*首付金额分布数据图表设置*/
            fisrtPayCountOption: {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {
                    data: ['金额']
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    boundaryGap: [0, 0.01]
                },
                yAxis: {
                    type: 'category',
                    data: []
                },

                toolbox: {
                    right: '20',
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {
                            type: ['line', 'bar']
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                dataZoom: [{
                    type: 'slider',
                    show: true,
                    yAxisIndex: [0],
                    start: 1,
                    end: 100
                }],
                series: [{
                    name: '金额',
                    type: 'bar',
                    data: [],
                    label: {
                        normal: {
                            show: true,
                            position: 'right'
                        }

                    }
                }]
            }
        }
    },
    computed: {
        xlsx() {
            return this.title + '.xlsx';
        }
    },
    methods: {
        chartsWidth(el) {
            if (document.getElementById(el) !== null) {
                document.getElementById(el).style.width = window.innerWidth - 261 + "px";
            }
        },
        //初始化
        _init() {
            var arr = ['fisrtPayCount', 'fisrtPayLevelByPlayer', 'fisrtPayLevelByCount', 'fisrtPayUpTo'];
            for (var x = 0; x < arr.length; x++) {
                this.chartsWidth(arr[x]);
                this[arr[x] + 'Charts'] = echarts.init(document.getElementById(arr[x]));
                this[arr[x] + 'Charts'].setOption(this.fisrtPayCountOption);
            }
            window.addEventListener('resize', function() {
                /*修改表格的宽度*/
                this.realTimeServiceTableWidth = document.body.clientWidth - 240 + "px";
                this.realTimeServiceContent = document.body.clientWidth - 220 + "px";

                for (var i in arr) {
                    this.chartsWidth(arr[i])
                }
                var resizeArr = ['fisrtPayCountCharts', 'fisrtPayLevelByPlayerCharts', 'fisrtPayLevelByCountCharts', 'fisrtPayUpToCharts']
                for (var j in resizeArr) {
                    this[resizeArr[j]].resize();
                }
            }.bind(this))
        },
        // 通用 成功 与 失败
        successFun(data) {
            this.$message({
                message: data,
                type: 'success'
            });
        },
        errorFun(data) {
            this.$message.error(data);
        },
        // 选择游戏的平台
        handleSelect(key, keyPath) {
            if (key === '4') {
                this.$refs.advance.filterShow = true;
            } else {
                this.postObj['platform'] = key;
            }
            this.getData(this.postObj);
        },
        // 改变时间
        dateChange(val) {
            if (val === undefined) {
                this.errorFun('请选择查看时间！')
            } else {
                var t = val.split(' - ')
                this.postObj.dstart = t[0];
                this.postObj.dend = t[1];
            }
            if (this.firstPayLevelChart.length > 0) {
                this.getData(this.postObj);
            }
        },
        // 获取服务器list 平台list  服务器list
        getList(url, choose) {
            var that = this;
            var pushData = function(pushArr, attr, data) {
                that[pushArr] = [];
                for (var i in data[attr]) {
                    that[pushArr].push({
                        value: i,
                        label: data[attr][i]
                    })
                }
            };
            this.$http.jsonp(`${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=${url}`, {
                params: { 'ps': choose }
            }).then(function(res) {
                var data = JSON.parse(JSON.parse(res.body));
                if (parseInt(data["res"]) === 0) {
                    // 后台select的数据
                    var lists = ["platformItmes", "channelItmes", "serverItmes"];
                    // 页面select名字
                    var nameLists = ["plats", "channels", "servers"];
                    for (var i = 0; i < lists.length; i++) {
                        if (data[lists[i]] !== undefined) {
                            pushData(nameLists[i], lists[i], data);
                        }
                    }
                } else {
                    this.getErrorMsg(Number(data.res))
                }
            })
        },
        // 获取数据
        getData: function(data) {
            var that = this;
            that.firstPayLevelChart = [];
            that.firstPayLevelChart1 = [];
            var p = new Promise(function(resolve, reject) {
                that.$http.jsonp(`${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=search`, {
                    params: { 'ps': `dstart=${data.dstart}&dend=${data.dend}&platform=${data.platform}&channel=${data.channel}&server=${data.server}&selectedType=${that.selectedType}` }
                }).then(function(res) {
                    resolve(res.body)
                })
            })
            p.then(function(value) {
                var data = JSON.parse(value)
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                if (parseInt(data["res"]) === 0) {
                    //首付金额分布charts
                    that.echartsChangeFirstPayCount(data);
                    //首付等级分布金额charts
                    that.firstPayLevelChart = data.firstPayLevelChart;
                    that.firstPayLevelChart1 = data.firstPayLevelChart1;
                    that.changePost(that.chartsName)
                        //新增到首次付费时长
                    that.echartsChangeFirstPayUpTo(data);
                } else {
                    that.errorFun(data['msg']);
                }
            })
        },
        //首付金额分布数据填充/改变
        echartsChangeFirstPayCount(data) {
            var that = this;
            //this.realLoadShow = false;
            if (data.firstPayCountChart === undefined) {
                var d = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var d = data['firstPayCountChart']['jsonStr'];
            }
            this.fisrtPayCountCharts.setOption({
                legend: {
                    data: d["names"]
                },
                yAxis: {
                    type: 'category',
                    data: that.escape2Html(d["columnkeys"])
                },
                series: [{
                    name: d["names"][0],
                    type: 'bar',
                    data: d["data"][0],
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#b8cff1' },
                                    { offset: 0.5, color: '#a99ce4' },
                                    { offset: 1, color: '#a07cdc' }
                                ]
                            )
                        },
                        emphasis: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#a07cdc' },
                                    { offset: 0.7, color: '#a99ce4' },
                                    { offset: 1, color: '#b8cff1' }
                                ]
                            )
                        }
                    },
                }]
            });
        },
        //首付等级分布数据填充/改变
        echartsChangeFirstPayLevel(data, levelchart) {
            var that = this;
            //this.realLoadShow = false;
            if (data === undefined) {
                var d = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var d = data['jsonStr'];
            }
            this[levelchart].setOption({
                grid: {
                    right: '5%',
                },
                dataZoom: [{
                    type: 'slider',
                    show: true,
                    yAxisIndex: [0],
                    start: 1,
                    end: 100,
                    right: '2%'
                }],
                legend: {
                    data: d["names"]
                },
                yAxis: {
                    type: 'category',
                    data: d["columnkeys"]
                },
                series: [{
                    name: d["names"][0],
                    type: 'bar',
                    data: d["data"][0],
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#66cf97' },
                                    { offset: 0.5, color: '#4eb59a' },
                                    { offset: 1, color: '#349b98' }
                                ]
                            )
                        },
                        emphasis: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#4eb59a' },
                                    { offset: 0.7, color: '#349b98' },
                                    { offset: 1, color: '#66cf97' }
                                ]
                            )
                        }
                    },
                }]
            });
        },
        //新增到首次付费时长数据填充/改变
        echartsChangeFirstPayUpTo(data) {
            var that = this;
            //this.realLoadShow = false;
            if (data.firstPayPlayTimeChart === undefined) {
                var d = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var d = data['firstPayPlayTimeChart']['jsonStr'];
            }
            this.fisrtPayUpToCharts.setOption({
                legend: {
                    data: d["names"]
                },
                yAxis: {
                    type: 'category',
                    data: that.escape2Html(d["columnkeys"])
                },
                series: [{
                    name: d["names"][0],
                    type: 'bar',
                    data: d["data"][0],
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#84ebd8' },
                                    { offset: 0.5, color: '#7fd2e2' },
                                    { offset: 1, color: '#7abde8' }
                                ]
                            )
                        },
                        emphasis: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#7abde8' },
                                    { offset: 0.7, color: '#7fd2e2' },
                                    { offset: 1, color: '#84ebd8' }
                                ]
                            )
                        }
                    },
                }]
            });
        },
        // 表格下载
        excel(tabelHead, data, val) {
            this.downloadExl(tabelHead, data, val, val);
        },
        //转义字符,这里的原始数据里的转义字符比较奇怪，所以这样处理两次：ex: &amp;lt;
        escape2Html(data) {
            var formatData = [];
            for (var x = 0; x < data.length; x++) {
                var str = data[x];
                var arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' };
                var tempStr = str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function(all, t) { return arrEntities[t]; });
                var newStr = tempStr.replace(/&(lt|gt|nbsp|amp|quot);/ig, function(all, t) { return arrEntities[t]; });
                formatData.push(newStr);
            }
            return formatData;
        },
        changeLevelType(target) {
            var label = target.label;
            this.changePost(label)
        },
        changePost(label) {
            var type = "";
            if (label == "人数" || label == "fisrtPayLevelByPlayerCharts") {
                type = "userCount";
                this.chartsName = "fisrtPayLevelByPlayerCharts";
                this.echartsChangeFirstPayLevel(this.firstPayLevelChart, "fisrtPayLevelByPlayerCharts");
            } else if (label == "金额" || label == "fisrtPayLevelByCountCharts") {
                type = "payCount";
                this.chartsName = "fisrtPayLevelByCountCharts";
                this.echartsChangeFirstPayLevel(this.firstPayLevelChart1, "fisrtPayLevelByCountCharts");
            }
        }
    },
    components: {
        'v-advance': advance
    },
    mounted() {
        // 初始化URL
        this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
        this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
        this.date = [new Date(new Date().getTime() - 8 * 86400000), new Date(new Date().getTime() - 86400000)];
        this.postObj.dstart = formatGMTDate(new Date(new Date().getTime() - 8 * 86400000), true);
        this.postObj.dend = formatGMTDate(new Date(new Date().getTime() - 86400000), true);
        this._init();
        // 获取到服务器 平台 渠道 list
        this.getList("initParam", "");

        //请求获取页面数据
        this.getData(this.postObj);
    }
}